package com.djx.commons.response;


import com.djx.entity.access.Permission;
import com.djx.entity.access.Role;
import com.djx.entity.access.User;
import lombok.Data;
import org.crazycake.shiro.AuthCachePrincipal;

import java.io.Serializable;
import java.util.*;

//用户的安全数据  1 给shiro授权 2 给前台,因为前台要展示不同的数据菜单
@Data
public class ProfileResult implements Serializable, AuthCachePrincipal {

    private String id;
    private String username;
    private String nickName;
    private String userLevel; //admin user
    private String userType;  // 1 是老师 2 是学生  (公用user表)  还会有student 和teacher表

    //角色集合
    private Map<String, Object> roles = new HashMap<>();

    /**
     * 普通用户
     * @param user
     */
    public ProfileResult(User user) {
        this.id = user.getId();
        this.username = user.getUsername();
        this.nickName = user.getNickName();
        this.userLevel = user.getUserLevel();
        this.userType = user.getUserType();

        //构造用户的的权限数据
        Set<Role> roles = user.getRoles();
        //分门别类 menu  point  api
        Set<String> menus = new HashSet<>();
        Set<String> points = new HashSet<>();
        Set<String> apis = new HashSet<>();


        for (Role role : roles) {
            Set<Permission> perms = role.getPermissions();
            for (Permission perm : perms) {
                String code = perm.getPermissionCode();
                if(perm.getPermissionType() == 1) {
                    menus.add(code);
                }else if(perm.getPermissionType() == 2) {
                    points.add(code);
                }else {
                    apis.add(code);
                }
            }
        }

        this.roles.put("menus", menus);
        this.roles.put("points", points);
        this.roles.put("apis", apis);
    }

    /**
     * admin专用
     * @param user
     * @param list
     */
    public ProfileResult(User user, List<Permission> list){//admin专用 查询出当前用户的所有权限
        this.id = user.getId();
        this.username = user.getUsername();
        this.nickName = user.getNickName();
        this.userLevel = user.getUserLevel();
        this.userType = user.getUserType();

        //构造用户的的权限数据
        //分门别类 menu  point  api
        Set<String> menus = new HashSet<>();
        Set<String> points = new HashSet<>();
        Set<String> apis = new HashSet<>();
        for (Permission perm : list) {
            String code = perm.getPermissionCode();
            if(perm.getPermissionType() == 1) {
                menus.add(code);
            }else if(perm.getPermissionType() == 2) {
                points.add(code);
            }else {
                apis.add(code);
            }
        }

        this.roles.put("menus", menus);
        this.roles.put("points", points);
        this.roles.put("apis", apis);
    }



    //shiro缓存
    @Override
    public String getAuthCacheKey() {
        return null;
    }
}
